import React from 'react'
import style from './style.pic-uploader'
import Link from '../link'
import IconFont from '../iconFont'

class PicUploader extends React.Component {

  static propsType = {
    add: React.PropTypes.func.required,
    clear: React.PropTypes.func.required,
    close: React.PropTypes.func.required,
    pics: React.PropTypes.array,
    show: React.PropTypes.bool
  }

  close() {
    this.props.close()
    this.props.clear()
  }

  handleClear({uuid}) {
    return () => {
      this.props.clear(uuid)
    }
  }

  handleAdd() {
    this.refs.file.click()
  }

  handleChange() {
    const { files } = this.refs.file
    const file = files[0]
    const { size, type, name } = file
    this.props.add(file)
  }

  renderItem = (v, i) => {
    if (v === '_') {
      if (i === 9) return null
      return (
        <li 
          onClick={::this.handleAdd}
          key={i} 
          className={style.add}
        >
          <Link icon="plus"/>
          <input type="file" ref="file" onChange={::this.handleChange}/>
        </li>
      )
    }
    else if (v._uuid) {
      return (
        <li className={style.loading} key={i}>
          <span>{v.file.name}</span>
        </li>
      )
    }
    return (
      <li className={style.image} style={{backgroundImage: `url(${v.url})`}} key={i}>
        <Link 
          onClick={::this.handleClear(v)}
          className={style.del} color="white" icon="close"/>
      </li>
    )
  }

  render() {
    const { show, pics } = this.props
		if (!show) return null
    return (
      <div className={style.root}>
        <ul>
          {
            pics.concat(['_']).map(this.renderItem)
          }
        </ul>
      </div>
    )
  }
}

export default PicUploader
